﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Imladris.Common.Interfaces;
using Imladris.DAL.BaseDataLayer;
using Imladris.DAL.DocumentBoundedContext;
using Imladris.Entities;

namespace Imladris.BUS.DocumentRepoUOW
{
    public class DocumentsRepo : IDocumentsRepo


    {
        private readonly DocumentContext _context;

        public DocumentsRepo(UnitOfWork uow)
        {
            _context = uow.Context;
        }

        public void Dispose()
        {
            _context.Dispose();
        }

        public IQueryable<Document> All
        {
            get { return _context.Documents; }
        }

        public IQueryable<Document> AllIncluding(params Expression<Func<Document, object>>[] includeProperties)
        {
            IQueryable<Document> query = _context.Documents;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Document Find(int id)
        {
            return _context.Documents.Find(id);
        }

        public void InsertOrUpdate(Document entity)
        {
            if (entity.DocumentID == default(int)) // New entity
            {
                _context.Entry(entity).State = EntityState.Added;
            }
            else        // Existing entity
            {
                _context.Entry(entity).State = EntityState.Modified;

            }
        }

        public void InsertOrUpdateGraph(Document dokumentGraph)
        {
            if (dokumentGraph.State == State.Added)
            {
                _context.Documents.Add(dokumentGraph);
            }
            else
            {
                _context.Documents.Add(dokumentGraph);
                _context.ApplyStateChanges();
            }
        }

        public void Delete(int id)
        {
            var document = _context.Documents.Find(id);
            _context.Documents.Remove(document);
        }
    }
}
